package com.taotao.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.common.utils.JsonUtils;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserService;

/**
 * 用户管理controller
 * @author leaf
 *
 */

@Controller
public class UserController {
	
	@Autowired
	private UserService userService; 
	
	@Value("${COOKIE_TOKEN_KEY}")
	private String COOKIE_TOKEN_KEY;
	
	@RequestMapping(value="/user/check/{param}/{type}",method=RequestMethod.GET)
	@ResponseBody
	public TaotaoResult verifyInfo(@PathVariable String param ,@PathVariable Integer type ){
		
		TaotaoResult result = userService.verifyInfo(param, type);
		return result;
	}
	
	@RequestMapping(value="/user/register",method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult resisterUser(TbUser user){
		TaotaoResult result = userService.registerUser(user);
		return result;
	}
	
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult userLogin(HttpServletRequest request, HttpServletResponse response,String username ,String password){
		TaotaoResult result = userService.login(username, password);
		String token = result.getData().toString();
		
		CookieUtils.setCookie(request, response, COOKIE_TOKEN_KEY, token);
		return result;
	}
	
	@RequestMapping(value="/user/token/{token}",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String checkToken(@PathVariable String token,String callback){
		TaotaoResult result = userService.checkToken(token);
		if(StringUtils.isNotBlank(callback)){
			String strResult = callback+"("+JsonUtils.objectToJson(result)+");";
			return strResult;
		}
		return JsonUtils.objectToJson(result);
	}
	
	@RequestMapping(value="/user/logout")
	@ResponseBody
	public TaotaoResult clearToken(HttpServletRequest request, HttpServletResponse response,String COOKIE_TOKEN_KEY){
		TaotaoResult result = userService.clearToken(COOKIE_TOKEN_KEY);
		return result;
	}
}

